package com.tool.app.utils;

import org.springframework.core.io.ClassPathResource;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;

/**
 * 响应流下载工具类
 */
public class HttpWriterUtil {
	public final static String UTF8 = "UTF-8";

	public static void writerFile(HttpServletResponse response, String fileName,String writeName) throws IOException {
		ClassPathResource pathResource = new ClassPathResource(fileName);
		try(InputStream inputStream = pathResource.getInputStream()) {
			writerFile(inputStream, response, writeName);
		} catch (IOException e) {
			throw e;
		}
	}

	public static void writerFile(InputStream inputStream, HttpServletResponse response, String writeName) throws IOException {
		try {
			//仅限本地文件获取类型
			String type = Files.probeContentType(new File(writeName).toPath());
			//若失败则调用下面的方法
			if (type == null) {
				//该方式支持本地文件，也支持http/https远程文件
				type = new MimetypesFileTypeMap().getContentType(new File(writeName));
			}
			response.setContentType(type);
			response.setCharacterEncoding(UTF8);
			response.setHeader("Content-Disposition", "attachment;filename=".concat(URLEncoder.encode(writeName, UTF8)));
			response.setHeader("Content-Length",String.valueOf(inputStream.available()));
		} catch (IOException e) {
			throw e;
		}
		try (
				OutputStream os = response.getOutputStream();
				BufferedInputStream bis = new BufferedInputStream(inputStream)
		) {
			byte[] buff = new byte[1024];
			int len;
			while ((len = bis.read(buff)) > 0) {
				os.write(buff, 0, len);
				os.flush();
			}
		} catch (IOException e) {
			throw e;
		}
	}


	public static void setContentType(HttpServletResponse response, String writeName) throws IOException {
		try {
			//仅限本地文件获取类型
			//String type = Files.probeContentType(new File(writeName).toPath());
			//若失败则调用下面的方法
			String type = new MimetypesFileTypeMap().getContentType(new File(writeName));
			if (type == null) {
				//该方式支持本地文件，也支持http/https远程文件
				type = new MimetypesFileTypeMap().getContentType(new File(writeName));
			}
			response.setContentType(type);
			response.setCharacterEncoding(UTF8);
			String name = URLEncoder.encode(writeName, UTF8);
			response.setHeader("Content-Disposition", "attachment;filename=".concat(name));
			//response.setHeader("Content-Length",String.valueOf(inputStream.available()));
		} catch (IOException e) {
			throw e;
		}
	}
}